﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.Controls.POSControls
{
    public partial class PurchaseLookupCtrl : BaseControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            txtIMEI.Focus();
            if (!IsPostBack)
            {
                editMode = false;
                ControlEditState();

                txtIMEI.MaxLength = SysVars.IMEILength;

                View_CategoryTree treeCategory = View_CategoryTree.GetCategoryTree();
                Utilities.LoadDropDownList(ddlCategory, treeCategory.DefaultView, View_CategoryTree.ColumnNames.Path, View_CategoryTree.ColumnNames.ID);

                Brands brand = Brands.LoadAllActiveBrands();
                brand.AddNew();
                brand.ID = 0;
                brand.BrandName = "--All--";
                brand.Sort = "ID asc";
                Utilities.LoadDropDownListNoSelectNoSort(ddlBrand, brand.DefaultView, Brands.ColumnNames.BrandName, Brands.ColumnNames.ID);

                RefreshProductDetail();
            }

            btnNew.Enabled = Branches.CurrentBranchID == SessionUser.BranchID;
            if (Branches.CurrentBranchID != SessionUser.BranchID)
                btnNew.OnClientClick = "";
        }

        protected void btnBarCode_OnClick(object sender, EventArgs e)
        {
            try
            {
                Products p = Products.GetProductByBarCode(txtBarCode.Text);
                if (p.RowCount > 0)
                {
                    ddlCategory.SelectedValue = p.s_CategoryID;
                    ddlBrand.SelectedValue = p.s_BrandID;
                    RefreshProduct();
                    if (ddlProduct.Items.Count > 1)
                    {
                        ddlProduct.SelectedValue = p.s_ID;
                        txtQuantity.Focus();
                        RefreshProductDetail();
                    }
                }
                else
                    ShowErrorMessage(mainPanel, "(*) Invalid Bar Code!");
            }
            catch (Exception ex)
            {
                ShowErrorMessage(mainPanel, ex.Message);
                ErrorLog.WriteToFile("SaleLookUp.ascx.cs", "btnBarCode_OnClick", ex.StackTrace);
            }
        }

        protected void btnNew_OnClick(object sender, EventArgs e)
        {
            if (Session[hidSessionID.Value] != null && Session[hidSessionID.Value] is Products)
            {
                Products p = (Products)Session[hidSessionID.Value];
                if (p.RowCount > 0)
                {
                    ddlCategory.SelectedValue = p.CategoryID.ToString();
                    ddlBrand.SelectedValue = p.BrandID.ToString();
                    RefreshProduct();
                    ddlProduct.SelectedValue = p.ID.ToString();
                }
            }
        }

        public string GetProductEditPageLink()
        {
            return Page.ResolveUrl("~/EditPages/EditProduct.aspx?");
        }

        String IncludeAllChildCategories()
        {
            int from = ddlCategory.SelectedIndex;
            if (from < 0)
                return "";
            String res = ddlCategory.SelectedValue.ToString();
            String selectedPath = ddlCategory.SelectedItem.Text;
            for (int i = from; i < ddlCategory.Items.Count; i++)
            {
                if (ddlCategory.Items[i].Text.StartsWith(selectedPath + " - "))
                    res += "," + ddlCategory.Items[i].Value;
            }

            if (res.EndsWith(","))
                res = res.Remove(res.Length - 1);
            return res;
        }

        protected void ddlCategory_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshProduct();
        }

        protected void ddlBrand_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshProduct();
        }

        protected void ddlProduct_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshProductDetail();
        }

        bool editMode
        {
            get { return (bool)ViewState["EditMode"]; }
            set { ViewState["EditMode"] = value; }
        }

        void ControlEditState()
        {
            lblSalePrice.Visible = !editMode;
            lblDealerPrice.Visible = !editMode;
            txtSalePrice.Visible = editMode;
            txtDealerPrice.Visible = editMode;
            btnEdit.Visible = !editMode && Branches.CurrentBranchID == SessionUser.BranchID && SessionUser.Admin;
            btnSave.Visible = editMode;
            btnCancel.Visible = editMode;
            lblCost.Visible = !editMode;
            txtCost.Visible = editMode;
        }

        protected void btnEdit_OnClick(object sender, EventArgs e)
        {
            editMode = true;
            ControlEditState();
        }

        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            if (ddlProduct.SelectedValue != "")
            {
                int pid = int.Parse(ddlProduct.SelectedValue);
                Products p = new Products();
                p.LoadByPrimaryKey(pid);
                if (p.RowCount > 0)
                {
                    p.s_SalePrice = txtSalePrice.Text;
                    p.s_DealerPrice = txtDealerPrice.Text;
                    p.s_Cost = txtCost.Text;
                    p.Save();

                    lblDealerPrice.Text = string.Format("{0:C}", p.DealerPrice);
                    lblSalePrice.Text = string.Format("{0:C}", p.SalePrice);
                    lblCost.Text = string.Format("{0:C}", p.Cost);
                }
            }

            editMode = false;
            ControlEditState();
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            if (ddlProduct.SelectedValue != "")
            {
                int pid = int.Parse(ddlProduct.SelectedValue);
                Products p = new Products();
                p.LoadByPrimaryKey(pid);
                if (p.RowCount > 0)
                {
                    txtSalePrice.Text = p.s_SalePrice;
                    txtDealerPrice.Text = p.s_DealerPrice;
                    txtCost.Text = p.s_Cost;
                }
            }

            editMode = false;
            ControlEditState();
        }

        private void RefreshProductDetail()
        {
            if (ddlProduct.SelectedIndex > 0)
            {
                Products p = new Products();
                p.LoadByPrimaryKey(int.Parse(ddlProduct.SelectedValue));

                if (!p.IMEIAvailable)
                {
                    lstIMEI.Items.Clear();
                    txtIMEI.Text = "";
                    txtQuantity.Text = "1";
                    txtSalePrice.Text = p.s_SalePrice;
                    txtDealerPrice.Text = p.s_DealerPrice;
                    txtCost.Text = p.s_Cost;
                    if(!p.IsColumnNull(Products.ColumnNames.DealerPrice))
                        lblDealerPrice.Text = string.Format("{0:C}", p.DealerPrice);
                    if (!p.IsColumnNull(Products.ColumnNames.SalePrice))
                        lblSalePrice.Text = string.Format("{0:C}", p.SalePrice);
                    if (!p.IsColumnNull(Products.ColumnNames.Cost))
                        lblCost.Text = string.Format("{0:C}", p.Cost);
                    ControlEditState();
                    divIMEI.Visible = false;
                    divQty.Visible = true;
                }
                else
                {
                    divIMEI.Visible = true;
                    divQty.Visible = false;
                }

                btnAdd.Enabled = true;
            }
            else
            {
                btnAdd.Enabled = false;
                divIMEI.Visible = false;
                divQty.Visible = false;
            }
        }

        void RefreshProduct()
        {
            if (ddlBrand.SelectedIndex >= 0 && ddlCategory.SelectedIndex > 0)
            {
                Products products = Products.GetAllProductByCategoriesBrand(IncludeAllChildCategories(), int.Parse(ddlBrand.SelectedValue));
                Utilities.LoadDropDownList(ddlProduct, products.DefaultView, Products.ColumnNames.ProductName, Products.ColumnNames.ID);
                if (ddlProduct.Items.Count > 0)
                {
                    ddlProduct.SelectedIndex = 0;
                    RefreshProductDetail();
                }
            }
        }

        public delegate void AddProduct(object sender, ListItemEventArgs e);
        AddProduct onAddProduct;

        public AddProduct OnAddProduct
        {
            get { return onAddProduct; }
            set { onAddProduct = value; }
        }

        public delegate void AddIMEI(object sender, ListItemEventArgs e);
        AddIMEI onAddIMEI;

        public AddIMEI OnAddIMEI
        {
            get { return onAddIMEI; }
            set { onAddIMEI = value; }
        }

        public void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstIMEI.SelectedIndex >= 0)
                lstIMEI.Items.RemoveAt(lstIMEI.SelectedIndex);
        }

        public void btnClear_Click(object sender, EventArgs e)
        {
            lstIMEI.Items.Clear();
        }

        protected void btnAdd_OnClick(object sender, EventArgs e)
        {
            if (divIMEI.Visible && onAddIMEI != null)
            {
                String[] imeis = new String[lstIMEI.Items.Count];
                for (int i = 0; i < lstIMEI.Items.Count; i++)
                {
                    imeis[i] = lstIMEI.Items[i].Value;
                }

                ListItemEventArgs arg = new ListItemEventArgs();
                arg.Data = new System.Collections.Hashtable();
                arg.Data["ProductID"] = int.Parse(ddlProduct.SelectedValue);
                arg.Data["IMEI"] = imeis;

                onAddIMEI(this, arg);
            }
            else if(onAddProduct != null)
            {
                ListItemEventArgs arg = new ListItemEventArgs();
                arg.Data = new System.Collections.Hashtable();
                arg.Data["ProductID"] = int.Parse(ddlProduct.SelectedValue);
                arg.Data["Quantity"] = int.Parse(txtQuantity.Text);

                onAddProduct(this, arg);
            }
        }

        protected void btnAddIMEI_OnClick(object sender, EventArgs e)
        {
            if (onAddIMEI != null)
            {
                if (ProductDetails.IsIMEIAvailable(txtIMEI.Text))
                {
                    ListItemEventArgs arg = new ListItemEventArgs();
                    arg.Data = new System.Collections.Hashtable();
                    arg.Data["IMEI"] = txtIMEI.Text;
                    onAddIMEI(this, arg);
                    txtIMEI.Text = "";
                    ScriptManager.RegisterStartupScript(this.Page, typeof(Page), Guid.NewGuid().ToString(), "focusIMEI();", true);
                }
                else
                    ShowErrorMessage(mainPanel, "(*) IMEI not available in stock!");
            }
        }

        protected void btnAddIMEI_Click(object sender, EventArgs e)
        {
            AddIMEIToList(txtIMEI.Text);
        }

        public void AddIMEIToList(string imei)
        {
            if (imei.Length == SysVars.IMEILength)
            {
                if (lstIMEI.Items.FindByValue(imei) == null)
                {
                    ListItem item = new ListItem(imei, imei);
                    lstIMEI.Items.Add(item);
                    txtIMEI.Text = "";
                }
                else
                {
                    ShowErrorMessage(mainPanel, "(*) IMEI " + txtIMEI.Text + " has been added." );
                    txtIMEI.Text = "";
                }
            }
        }
    }
}